﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ForceController : EventBehaviour {
    public float radius = 0.5f;
    public float power = 0f;
    public float upwardsModifier = 0f;
    public MeshFilter meshFilter;
    public bool randomOnCenter = true;

    Transform _transform;
    Camera _camera;

    void Start() {
        _transform = GetComponent<Transform>();
        _camera = _transform.root.GetComponentInChildren<Camera>();
    }

    public static bool isDraging;

    public override void OnBeginDrag(PointerEventData eventData) {
        ChineseRestaurantManager.Instance.EnableFloater(false);
        isDraging = true;
    }

    public override void OnDrag(PointerEventData eventData) {
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;

        if (Physics.Raycast(ray, out hitInfo)) {
            power = (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) ? 5f : 3f;

            if (!Application.isEditor) {
                power *= 2f;
            }

            ApplyExplosionForce(hitInfo.point);
        }
    }

    public override void OnEndDrag(PointerEventData eventData) {
        power = 0f;
        ChineseRestaurantManager.Instance.EnableFloater(SwitchController.IsOn ? false : true);
        isDraging = false;
    }

    void FixedUpdate() {
        if (isDraging || !SwitchController.IsOn) {
            return;
        }

        RandomApplyForce();
    }

    void RandomApplyForce() {
        if (meshFilter == null) {
            meshFilter = GetComponent<MeshFilter>();
        }

        if (meshFilter) {
            if (randomOnCenter) {
                ApplyExplosionForce(meshFilter.transform.position);
                return;
            }

            var vertices = meshFilter.mesh.vertices;
            var index = Random.Range(0, vertices.Length);
            var worldPos = _transform.TransformPoint(vertices[index]);
            ApplyExplosionForce(worldPos);
        }
    }

    public void ApplyExplosionForce(Vector3 explosionPos) {
        PhysicsUtility.ApplyExplosionForce(explosionPos, radius, power, upwardsModifier);
    }
}
